<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Db;


class Xcx extends Base
{
    /**
     * 获取用户授权信息
     * @return [type] [description]
     */
    public function getInfo(){
        // 登陆
        if($this->uid>0){
            // 输出
            return json([
                    'code'      => 200,
                    'dest'      => 'success',
                    'data'      => ''
                ]);

        // 未登录
        }else{
            return json([
                    'code'      => 400,
                    'dest'      => 'error',
                    'data'      => ''
                ]);
        }
    }


    /**
     * 首页 -- banner图信息
     * @return [type] [description]
     */
    public function index()
    {
        // banner信息
        $info = Db::name('banner')->where('is_show',1)->where('is_del',0)->order('sort desc')->select();

        // 公告
        $notice = Db::name("notice")->where('is_show',1)->select();

        // 输出
        return json([
                'code'          => 200,
                'dest'          => 'success',
                'data'          => $info,
                'notice'        => $notice
            ]);
        //'is_manager'    => $this->admin,

    }



    /**
     * 股票列表页
     * @return [type] [description]
     */
    public function lists()
    {
        $type = input('');  // 类型： remark 个股点评 ， recomm 个股推荐 ， share 精华分享

        if(!$type['type']){
            return json([
                    'code'      => 400,
                    'dest'      => '参数不完整',
                    'data'      => ''
                ]);
        }

        $page       = input('page')     ? input('page')     : 1;                                   // 页码
        $pageSize   = input('limit')    ? input('limit')    : config('paginate')['list_rows'];     // 每页显示条数

        // 排序
        // $sort       = input('sort')     ? input('sort').' desc'     : 'enlist desc';
        $be_sort    = input('sort',0);
        
        if($be_sort == 1){

            $gupiao_sort = Session::get("gupiao_sort");

            switch ($gupiao_sort) {
                case 'enlist':
                    Session::set("gupiao_sort","last_live_time");
                    break;
                
                case 'last_live_time':
                    Session::set("gupiao_sort","enlist");
                    break;

                default:
                    Session::set("gupiao_sort","enlist");
                    break;
            }

        }else{

            if(Session::get("gupiao_sort") == null){
                Session::set("gupiao_sort","enlist");
            }
            
        }

        $sort       = Session::get("gupiao_sort")." desc";


        $where = 1;

        switch ($type['type']) {

            // 个股点评
            case 'remark':
                // 检索条件
                input('keyword') == null || $where = ['name|short_name|code'=>['like','%'.input('keyword').'%']]; 

                $list=Db('gupiao')
                    ->where('is_show',1)
                    ->where('is_recomm',0)
                    ->where($where)
                    ->order($sort)
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
                break;
            // -------------------------------------------------------------
            // 个股推荐
            case 'recomm':          
                // 检索条件
                input('keyword') == null || $where = ['name|short_name|code'=>['like','%'.input('keyword').'%']]; 

                $list=Db('gupiao')
                    ->where('is_show',1)
                    ->where('is_recomm',1)
                    ->where($where)
                    ->order($sort)
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
                break;
            // -------------------------------------------------------------  
            // 精华分享
            case 'share':
                // 检索条件
                input('keyword') == null || $where = ['title'=>['like','%'.input('keyword').'%']]; 

                $list = Db('article')
                        ->where('is_show',1)
                        ->where('is_del',0)
                        ->where($where)
                        ->order('update_time desc')
                        ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                        ->toArray();

                break;
            // -------------------------------------------------------------
            default:
                return json([
                        'code'      => 400,
                        'dest'      => '参数不完整',
                        'data'      => ''
                    ]);
                break;
        }

        // 12小时内为最新
        $ago_12h = time()-12*60*60;

        if($type['type'] == 'share'){
            // 格式化时间
            if($list['data']){
                foreach ($list['data'] as $key => $value) {
                    $list['data'][$key]['create_time'] = date('Y-m-d',$value['create_time']);
                    $list['data'][$key]['update_time'] = date('Y-m-d',$value['create_time']);
                    if($value['create_time']>$ago_12h){
                        $list['data'][$key]['is_new']       = 1;
                    }else{
                        $list['data'][$key]['is_new']       = 0;
                    }
                }
            }

        } else {
            if($list['data']){
                foreach ($list['data'] as $key => $value) {
                    $list['data'][$key]['create_time'] = date('Y-m-d',$value['create_time']);
                    $list['data'][$key]['update_time'] = date('Y-m-d',$value['create_time']);

                    if($list['data'][$key]['last_live_time']>0){
                        $list['data'][$key]['last_live_time'] = date('m-d H:i',$value['last_live_time']);
                    }else{
                        $list['data'][$key]['last_live_time'] = '-- 未更新 --';
                    }
                    

                    if($value['last_live_time']>$ago_12h){
                        $list['data'][$key]['is_new']       = 1;
                    }else{
                        $list['data'][$key]['is_new']       = 0;
                    }
                }
            }

        }


        // 输出数据
        return json([
                'code'          => 200,
                'dest'          => 'success',
                'data'          => $list['data'],
                'count'         => count($list['data']),
            ]);

    }




    /**
     * 直播间列表
     * @return [type] [description]
     */
    public function lives()
    {
        $gupiao_id = input('id');

        // 正在点评中直播
        $lives_ing = Db('lives')
                    ->field('id,title,begin_time,price')
                    ->where('gupiao_id',$gupiao_id)
                    ->where('state',0)
                    ->order("create_time desc")
                    ->find();
        // 用户是否购买点评
        if($lives_ing){

            // 格式化开始
            $lives_ing['begin_time']    = date('Y-m-d H:i:s',$lives_ing['begin_time']);

            $is_buy     = Db('orders')->where('live_id',$lives_ing['id'])->where('status',1)->where('uid',$this->uid)->find();
            if($is_buy){
                $lives_ing['is_buy']    = 1;
            }else{
                $lives_ing['is_buy']    = 0;
            }

            // 用户余额
            $lives_ing['balance'] = $this->balance;
        }

        // 历史点评
        $lives_ago = Db('lives')->field('id,title,begin_time')->where('gupiao_id',$gupiao_id)->where('state',1)->select();
        if($lives_ago){
            foreach ($lives_ago as $key => $value) {
                $lives_ago[$key]['begin_time'] = date('Y-m-d H:i:s',$value['begin_time']);
            }
        }

        // 输出数据
        return json([
                'code'          => 200,
                'dest'          => 'success',
                'lives_ing'     => $lives_ing,
                'lives_ago'     => $lives_ago
            ]);

    }



    /**
     * 用户是否购买过
     * @return [type] [description]
     */
    public  function order(){

        // 直播间id
        $id = input('id');

        $buy_ago = Db('orders')
                ->where('live_id',$id)
                ->where('uid',$this->uid)
                ->find();

        if($buy_ago){

            $this->success();

        } else {

            $this->error();

        }
    }




    /**
     * 购买下单
     * url :index/xcx/buy
     * @return [type] [description]
     */
    public function buy()
    {
        if(!input('id')){
            return json([
                    'code'      => 400,
                    'dest'      => '参数不完整'
                ]);
        }

        // 用户授权信息是否完整
        if(!$this->uid){
            return json([
                    'code'      => 401,
                    'dest'      => '未授权'
                ]);
        }

        // 直播间id
        $id     = input('id');

        // 用户信息
        $user_info  = Db('users')->where('id',$this->uid)->find();
        if(!$user_info){
            return json([
                    'code'      => 400,
                    'dest'      => '用户授权信息失效'
                ]);
        }

        // 初始化变量 -- 是否已经生成订单
        $is_orders = 0;

        // 用户是否已经购买本直播间课程
        $buy_ago = Db('orders')
            ->where('live_id',$id)
            ->where('uid',$this->uid)
            ->find();
        if($buy_ago){
            if($buy_ago['status'] == 1){
                return json([
                        'code'      => 200,
                        'dest'      => '已购买',
                        'order_id'  => $buy_ago['order_id'],
                        'live_id'   => $buy_ago['live_id'],
                        'status'    => $buy_ago['status']
                    ]);
            }elseif($buy_ago['status'] == 0){
                $is_orders = 1;
            }
        }

        // 直播间信息
        $lives_info = Db('lives')->field('id,title,uid,price,gupiao_id')->where('id',$id)->find();

        // 增加股票点击量
        $re = Db("gupiao")->where('id',$lives_info['gupiao_id'])->setInc("enlist",1);

        // 余额是否充足
        if($user_info['balance'] < $lives_info['price']){
            return json([
                    'code'      => 402,
                    'dest'      => '余额不足'
                ]);
        }

        // 扣费
        if($lives_info['price'] > 0){

            $re_pay = Db('users')->where('id',$this->uid)->update(['balance'=>$user_info['balance']-$lives_info['price']]);

        }else{

            $re_pay = true;

        }

        if($re_pay){

            // 更改订单状态
            if($is_orders == 1){

                $re = Db('orders')->where('id',$buy_ago['id'])->update(['status'=>1]);

            }else{
                if($lives_info['id']){

                    // 插入订单数据
                    $params['order_id']     = time().rand(1000,9999).$this->uid;        // 订单编号
                    $params['uid']          = $this->uid;
                    $params['username']     = $this->username;
                    $params['photo']        = $this->photo;
                    $params['live_id']      = $lives_info['id'];                        // 直播id
                    $params['live_name']    = $lives_info['title'];                     // 直播名称
                    $params['zhubo_id']     = $lives_info['uid'];                       // 主播id
                    $params['amount']       = $lives_info['price'];                     // 支付金额
                    $params['create_time']  = time();
                    $params['update_time']  = time();
                    $params['status']       = 1;

                    $re = Db('orders')->insert($params);

                }else{

                    return json([
                        'code'      => 400,
                        'dest'      => '无效的直播间'
                    ]);

                }

            }

            // 返回数据
            if($re){
                return json([
                        'code'      => 200,
                        'dest'      => '购买成功'
                    ]);
            }else{
                return json([
                        'code'      => 400,
                        'dest'      => '网络错误'
                    ]);
            }
        }else{
            return json([
                        'code'      => 400,
                        'dest'      => '网络错误'
                    ]);
        }
    }


    public function up_video()
    {
        $up_video = new up_video($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);

        $up_video->apiReturn();

    }




}
